local DatiExcel = require("excel.Dati")
local DailyActFL = require("activity.DailyActFL")
local LvConfig = require("excel.LevelReward")[7]
local CopyL = require("copy.CopyL")
local Map = require("core.Map")
local CopyDefine = require("copy.Define")
local ExcelMap = require("excel.Map")
local CopyConfig = ExcelMap.copy
local Buffer = require("buffer.Buffer")
local ObjHuman = require("core.ObjHuman")
local Broadcast = require("broadcast.Broadcast")
local Lang = require("common.Lang")
local Msg = require("core.Msg")
local ActDefine = require("activity.Define")
local rewardConfig = DatiExcel.reward
local Grid = require("bag.Grid")
local DailyActDefine = require("activity.Define")
local MailLogicFL = require("mail.MailLogicFL")
local Cmds     = require("buffer.Cmds")
local Status = require("scene.Status")
local Buffer = require("buffer.Buffer") 

CURRENT_QUESTION = CURRENT_QUESTION or {}  --当前问题
CURRENT_ROOM_ID = CURRENT_ROOM_ID or {} --roomID
IS_SEND_MAIL = IS_SEND_MAIL or {} --是否发送邮件
DATI_HEART_COUNT = DATI_HEART_COUNT or {} 

--检查问题是否重复
function checkRepeat(rand)
  if CURRENT_QUESTION then
    for i=1, #CURRENT_QUESTION do
      if CURRENT_QUESTION[i] == rand then
        return false
      end
    end
  end
  return true
end
--得到从多少开始计数
function getStartTime(roomID)
  local nActData = DailyActFL.onGetActData(ActDefine.ACT_TYPE_DATI_ACT)
  if not nActData or nActData.status ~= ActDefine.ACT_STATE_RUNNING then
      DATI_HEART_COUNT[roomID] = 0
  end
  DATI_HEART_COUNT[roomID] = os.time() - nActData.startTime  
end
--得到问题
function getQuetion(roomID)
  if DATI_HEART_COUNT[roomID] ~= (#CURRENT_QUESTION + 1) * 30 and #CURRENT_QUESTION ~= 0 then
    return
  end
  local rand = math.random(1,#DatiExcel.question)
  for i=1, 100 do
    if checkRepeat(rand) then
      break
    else
      rand = math.random(1,#DatiExcel.question)
    end
  end
  CURRENT_QUESTION[#CURRENT_QUESTION + 1] = rand
end
function showExp(human)
  local sendMsg = Msg.gc.GC_COPY_DATI_ADD_EXP
  sendMsg.addExp = human.datiTotalAddExp
  Msg.send(sendMsg, human.fd)
end
--增加经验
function addExp(human, area, roomID)
  if DatiExcel.question[CURRENT_QUESTION[#CURRENT_QUESTION]].answer == area then
    ObjHuman.addExp(human, LvConfig[human.db.lv].exp)
    human.datiRightCnt = human.datiRightCnt + 1
    human.datiTotalAddExp = human.datiTotalAddExp + LvConfig[human.db.lv].exp
    human.DatiRight = 1
    Buffer.removeID(DatiExcel.define[1].bufPig, human)
  else    
    Buffer.add(DatiExcel.define[1].ben1, human, human)
    ObjHuman.addExp(human, math.floor(LvConfig[human.db.lv].exp * CopyDefine.DATI_FAIL_PERCENT))
    human.datiTotalAddExp = human.datiTotalAddExp + math.floor(LvConfig[human.db.lv].exp * CopyDefine.DATI_FAIL_PERCENT)
    Buffer.add(DatiExcel.define[1].bufPig, human, human)
    human.DatiRight = 0
  end
  showExp(human)
end
--显示问题
function showQuestion(copyID, roomID, human)
  if #CURRENT_QUESTION == 0 then
    getQuetion(roomID)
  end
  local config = DatiExcel.question[CURRENT_QUESTION[#CURRENT_QUESTION] ]
  local sendMsg = Msg.gc.GC_COPY_DATI_SHOW_SUBJECT
  sendMsg.remain_time = 20 - DATI_HEART_COUNT[roomID] % CopyDefine.DATI_ONE_NEED_TIME
  sendMsg.content = config.question
  sendMsg.choice1 = config.choice1
  sendMsg.choice2 = config.choice2
  sendMsg.answer = config.answer
  sendMsg.question_cnt = math.floor((DATI_HEART_COUNT[roomID] - 30) / CopyDefine.DATI_ONE_NEED_TIME) + 1
  if sendMsg.question_cnt < 0 or sendMsg.question_cnt > CopyDefine.DATI_ONE_NEED_TIME then
    sendMsg.question_cnt = 0
  end
  if human then
    Msg.send(sendMsg, human.fd)
  else
    CopyL.sendCopy(sendMsg, copyID, roomID)
  end  
end
--显示下一次问题
function showNextQuestion(human, copyID, roomID, isFirst)
  local sendMsg = Msg.gc.GC_COPY_DATI_SHOW_REMAIN
  sendMsg.remain_time = CopyDefine.DATI_ONE_NEED_TIME - DATI_HEART_COUNT[roomID] % CopyDefine.DATI_ONE_NEED_TIME
  sendMsg.remain_cnt = 30 - math.floor((DATI_HEART_COUNT[roomID] - 30) / CopyDefine.DATI_ONE_NEED_TIME) - 1
  sendMsg.right_cnt = human and human.datiRightCnt or 0
  sendMsg.is_first = isFirst and isFirst or 1
  if isFirst then
    sendMsg.remain_time = 30 - DATI_HEART_COUNT[roomID]
    sendMsg.remain_cnt = 30
  end
  if sendMsg.remain_cnt < 0 or sendMsg.remain_time < 0 then
    sendMsg.remain_cnt = 0
    sendMsg.remain_time = 0
  end
  if human then
    Msg.send(sendMsg, human.fd)
  else
    CopyL.sendCopy(sendMsg, copyID, roomID)
  end
end
--当前答题人数排序
function sortFunc(objA, objB)
  return objA.datiRightCnt > objB.datiRightCnt
end
--发送排行榜
function sendRankList(copyID, roomID, human)
  local sendMsg = Msg.gc.GC_COPY_DATI_SHOW_RANK
  local humanList = CopyL.getCopyHumanList(copyID, roomID)
  table.sort(humanList, sortFunc)
  local len = #humanList > 3 and 3 or #humanList
  sendMsg.rank[0] = len
  for i=1, len do
    sendMsg.rank[i].name = humanList[i].name
    sendMsg.rank[i].uuid = humanList[i]._id
    sendMsg.rank[i].cnt = humanList[i].datiRightCnt
  end
  if human then
    Msg.send(sendMsg, human.fd)
  else
    CopyL.sendCopy(sendMsg, copyID, roomID)
  end
end
--发送特效
function sendTexiao(copyID, roomID, humanList)
  local sendMsg = Msg.gc.GC_COPY_DATI_SHOW_TEXIAO
  sendMsg.list[0] = #humanList
  for i=1, #humanList do
    sendMsg.list[i].uuid = humanList[i]._id
    sendMsg.list[i].status = humanList[i].DatiRight or 0
  end
  CopyL.sendCopy(sendMsg, copyID, roomID)
end
--发送奖励列表
function sendReward(human)
  local sendMsg = Msg.gc.GC_COPY_DATI_SHOW_REWARD
  local cache = {}
  sendMsg.reward[0] = #rewardConfig
  for i=1, #rewardConfig do
    Grid.create(cache, rewardConfig[i].itemID, 1)
    Grid.makeItem(cache, sendMsg.reward[i].item, 0, human)
    sendMsg.reward[i].needCnt = rewardConfig[i].cnt
    Grid.create(cache, rewardConfig[i].reward, 1)
    Grid.makeItem(cache, sendMsg.reward[i].beforeReward, 0, human)
  end
  Msg.send(sendMsg, human.fd)
end

--答题每秒定时器
function onDatiOneSec(copyID, roomID)
  DATI_HEART_COUNT[roomID] = DATI_HEART_COUNT[roomID] + 1 
  if DATI_HEART_COUNT[roomID] > CopyDefine.DATI_ONE_NEED_TIME * 31 - 10 + 1 then
    if not IS_SEND_MAIL[roomID] then
      sendMail(copyID, roomID)
      local humanList = CopyL.getCopyHumanList(copyID, roomID)
      for i=1, #humanList do
        showNextQuestion(humanList[i], copyID, roomID, 2)
      end
      IS_SEND_MAIL[roomID] = true
      return
    else
      return
    end
  end
  
  local nCopyConfig = CopyConfig[copyID]
  local mapID = nCopyConfig.mapList[1]
  if DATI_HEART_COUNT[roomID] <= 29 then
    return
  elseif DATI_HEART_COUNT[roomID] % CopyDefine.DATI_ONE_NEED_TIME == 0 then
    getQuetion(roomID)
    showQuestion(copyID, roomID)
  elseif DATI_HEART_COUNT[roomID] % CopyDefine.DATI_ONE_NEED_TIME == 20 then
    --结算奖励，增加buf  
    local humanList = CopyL.getCopyHumanList(copyID, roomID)
    for i=1, #humanList do
      if Map.is_in_area_id(mapID, humanList[i].x, humanList[i].y, CopyDefine.DATI_AREA_1) then
        addExp(humanList[i], CopyDefine.DATI_AREA_1, roomID)
      elseif Map.is_in_area_id(mapID, humanList[i].x, humanList[i].y, CopyDefine.DATI_AREA_2) then
        addExp(humanList[i], CopyDefine.DATI_AREA_2, roomID)
      else
        addExp(humanList[i], CopyDefine.DATI_AREA_3, roomID)
      end
      showNextQuestion(humanList[i], copyID, roomID)
    end
    sendRankList(copyID, roomID)
    sendTexiao(copyID, roomID, humanList)    
  end  
end
--进入副本
function onDatiHumanEnterCopy(human, copyID, roomID)
  Buffer.add(DatiExcel.define[1].buf, human, human)
  Status.sendViewStatus(human,true)
  if DATI_HEART_COUNT[roomID] > CopyDefine.DATI_ONE_NEED_TIME * 31 - 10 then
    showNextQuestion(human, copyID, roomID, 2)
    sendRankList(copyID, roomID)
    sendReward(human)
    return
  end
  if DATI_HEART_COUNT[roomID] < 29 then
    showNextQuestion(human, copyID, roomID, 0)
  elseif DATI_HEART_COUNT[roomID] % CopyDefine.DATI_ONE_NEED_TIME >= 0 and DATI_HEART_COUNT[roomID] % CopyDefine.DATI_ONE_NEED_TIME < 20 then
    showQuestion(copyID, roomID, human)
  elseif DATI_HEART_COUNT[roomID] % CopyDefine.DATI_ONE_NEED_TIME >= 20 and DATI_HEART_COUNT[roomID] % CopyDefine.DATI_ONE_NEED_TIME < 30 then
    showNextQuestion(human, copyID, roomID)
  end
  sendRankList(copyID, roomID, human)
  showExp(human)
  sendReward(human)
end

function checkEnter(human)--, copyID, roomID)
  if not DailyActFL.onCheckActIsRunning(ActDefine.ACT_TYPE_DATI_ACT) then
    Broadcast.sendBroadcast(human, Lang.DOWN, Lang.COPU_DATI_NOT_START)  --活动暂未开启
    return false
  end
  if Cmds.passive.awake(human) then
    Broadcast.sendBroadcast(human, Lang.DOWN, Lang.COPY_DATI_IS_AWAKE)
    return false
  end
  return true
end
--离开副本
function onDatiHumanLeaveCopy(human)--, copyID, roomID)
  Buffer.removeID(DatiExcel.define[1].buf, human)
  human.datiRightCnt = 0
end

function sendMail(copyID, roomID)
  local humanList = CopyL.getCopyHumanList(copyID, roomID)
  table.sort(humanList, sortFunc)
  for i=1, #humanList do
    local nGridList = {}
    if i <= 3 then
      nGridList[1] = Grid.create(nil, rewardConfig[i].reward, 1, 1)
      MailLogicFL.CreateNewMailForUser(humanList[i]._id, string.format("智斗群雄活动第%d名奖励", i), "由于您在智斗群雄活动中的优异表现，特将奖励发给您", nGridList)
    end
    for j=1, #rewardConfig do
      if humanList[i].datiRightCnt >= rewardConfig[j].cnt then        
        nGridList[1] = Grid.create(nil, rewardConfig[j].itemID, 1, 1)
        MailLogicFL.CreateNewMailForUser(humanList[i]._id, "智斗群雄活动奖励", "由于您在智斗群雄活动中的优异表现，特将奖励发给您", nGridList)
        break
      end
    end
  end
end

function onDatiRoomEnd()--actData, arg)
  for i=1, #CURRENT_ROOM_ID do
    CopyL.roomFinish(CopyDefine.COPY_DATI_ID, CURRENT_ROOM_ID[i], CopyDefine.COPY_FINISH_ACT_END, "活动结束")
    CopyL.roomClear(CopyDefine.COPY_DATI_ID, CURRENT_ROOM_ID[i])    
  end
  IS_SEND_MAIL = {}
  DATI_HEART_COUNT = {}
  CURRENT_ROOM_ID = {}
  CURRENT_QUESTION = {}
end

function onDatiRoomBegin(copyID, roomID)
  for i=1, #CURRENT_ROOM_ID do
    if CURRENT_ROOM_ID[i] == roomID then
      return
    end
  end  
  CURRENT_ROOM_ID[#CURRENT_ROOM_ID + 1] = roomID
  IS_SEND_MAIL[roomID] = false
  getStartTime(roomID)  
end


DailyActFL.onRegisterCallBack(DailyActDefine.ACT_TYPE_DATI_ACT, nil, nil, onDatiRoomEnd)
